﻿using AutoMapper;
using Azure;
using MediatR;
using RedDragon.Common.Domain.Manufacture;
using RedDragon.Common.Domain.MaterialManagements;
using RedDragon.Common.Domain.Process;
using RedDragon.Common.Dtos;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.ErroCodeEnum;
using SqlSugar;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.Proccess
{
    /// <summary>
    /// 获取工艺路线工序行
    /// </summary>
    public class SearchOperationHandler : IRequestHandler<SearchOperationCommand, Result<PageResultDto<OperationsDto>>>
    {
        private readonly ISqlSugarClient _db;
        /// <summary>
        /// 工艺工序表
        /// </summary>
        private readonly IBaseRepository<ProcessLineOperations> _processLineOperationRepository;

        /// <summary>
        /// 工艺路线表
        /// </summary>
        private readonly IBaseRepository<ProcessRoutes> _processRouteRepository;

        /// <summary>
        /// 工序表
        /// </summary>
        private readonly IBaseRepository<Process> _processRepository;


        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SearchOperationHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="processLineOperationRepository"></param>
        /// <param name="processRouteRepository"></param>
        /// <param name="processRepository"></param>
        /// <param name="db"></param>
        /// <param name="logger"></param>
        public SearchOperationHandler(IBaseRepository<ProcessLineOperations> processLineOperationRepository,
                                      IBaseRepository<ProcessRoutes> processRouteRepository,
                                      IBaseRepository<Process> processRepository,
                                      ISqlSugarClient db,
                                      ILogger<SearchOperationHandler> logger)
        {
            _processLineOperationRepository = processLineOperationRepository;
            _processRouteRepository = processRouteRepository;
            _processRepository = processRepository;
            _db = db;
            _logger = logger;
        }

        /// <summary>
        /// 获取工艺路线工序
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result<PageResultDto<OperationsDto>>> Handle(SearchOperationCommand request, CancellationToken cancellationToken)
        {
            var result = new Result<PageResultDto<OperationsDto>>() { Code = (int)CommonErrorCode.Search };
            //实例化工艺路线工序
            var page = new PageResultDto<OperationsDto>() { TotalCount = 0, PageCount = 0, List = new List<OperationsDto>() };
            try
            {
                //总条数
                RefAsync<int> totalCount = 0;
                //总页数
                RefAsync<int> totalPage = 0;
                //查询数据
                var query = _db.Queryable<ProcessRoutes, ProcessLineOperations, Process, WorkCenters>((p, o, c, w) => p.ProcessRouteNo == o.ProcessRouteNo && o.ProcessId == c.ProcessId && c.WorkCentreCode == w.WorkCenterCode)
                    .Select((p, o, c, w) => new OperationsDto()
                    {
                        OperationId = o.OperationId,
                        OrderNum = o.OrderNum,
                        ProcessRouteNo = o.ProcessRouteNo,
                        ProcessId = o.ProcessId,
                        LeadTime = o.LeadTime,
                        LabourPrice = o.LabourPrice,
                        LostButton = o.LostButton,
                        Abstract = o.Abstract,
                        OperationStatus = o.OperationStatus,
                        CreatedOwner = o.CreatedOwner,
                        CreatedTime = o.CreatedTime,
                        ProcessNumber = c.ProcessNumber,
                        ProcessName = c.ProcessName,
                        WorkCenterCode = c.WorkCentreCode,
                        WorkCenterName = w.WorkCenterName,
                    });
                //工艺路线编码
                if (!string.IsNullOrEmpty(request.ProcessRouteNo))
                {
                    query = query.Where(p => p.ProcessRouteNo == request.ProcessRouteNo);
                }
                var list = await query.ToPageListAsync(request.PageIndex, request.PageSize, totalCount, totalPage);
                //总条数
                page.TotalCount = totalCount;
                //总页数
                page.PageCount = totalPage;
                //跳过几条显示几条
                page.List = list;
                if (page.List.Any())
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Data = page;
                    result.Msg = "获取工艺路线列表成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "获取工艺路线工序行异常" + ex.Message;
                _logger.LogError("获取工艺路线工序行异常" + ex.Message);
            }
            return result;
        }
    }
}
